﻿// owner 蒋家伟

#include "ExcelReader.h"
#include "Dbg_Warn_Define.h"

using namespace jsdk;

OwnerPtr<jsdk::ExcelReader> jsdk::ExcelReader::create(const std::wstring& fileName)
{
    OwnerPtr<jsdk::ExcelReader> opExcel = NEW_AS_OWNERPTR(ExcelReader);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opExcel, L"Excel对象创建失败", L"蒋家伟", L"2023-09-15");
#ifdef _MSC_VER
    try
    {
        opExcel->m_workBook.load(fileName);
    }
    catch (xlnt::exception excption)
    {
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(false, StringUtils::toWString(excption.what()), L"蒋家伟", L"2023-10-23");
    }
#else
    try
    {
        opExcel->m_workBook.load(StringUtils::toString(fileName));
    }
    catch (xlnt::exception excption)
    {
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(false, StringUtils::toWString(excption.what()), L"蒋家伟", L"2023-10-23");
    }
#endif // _MSVC
    return std::move(opExcel);
}

jsdk::ExcelReader::~ExcelReader()
{
}

bool jsdk::ExcelReader::openSheet(uint64_t sheetIndex)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(sheetIndex < m_workBook.sheet_count(), L"index 越界， 当前excel没有对应index的sheet。 Index ： " + StringUtils::toWString(sheetIndex), L"蒋家伟", L"2023-09-25");
    m_workSheet = m_workBook.sheet_by_index(sheetIndex);
    m_excelData.swap(std::vector<std::vector<std::wstring>>{});
    for (const auto& row : m_workSheet.rows(false))
    {
        std::vector<std::wstring> cells;
        for (const auto&  cell : row)
        {
            cells.push_back(StringUtils::toUTF8WString(cell.value<std::string>()));
        }
        m_excelData.push_back(std::move(cells));
    }

    return true;
}

const std::wstring* jsdk::ExcelReader::getCellData(uint64_t row, uint64_t col) const
{
    if (m_excelData.empty())
        return nullptr;
    if (row < m_excelData.size() && col < m_excelData[0].size())
    {
        return &m_excelData[row][col];
    }
    return nullptr;
}

uint64_t jsdk::ExcelReader::getSheetRowCount() const
{
    return m_excelData.size();
}

uint64_t jsdk::ExcelReader::getSheetColCount() const
{
    if (m_excelData.empty())
        return 0;
    return m_excelData[0].size();
}
